import axios from "axios";

const instance = axios.create({
    baseURL: 'http://localhost:3000/',
    timeout: 3000
})

instance.interceptors.request.use((request) => {
    const login = JSON.parse(localStorage.getItem('login'))
    if (login) {
        request.headers.Authorization = `Bearer ${login.access_token}`
    }
    const token = localStorage.getItem('token')
    if (token) {
        request.headers.Authorization = `Bearer ${token}`
    }
    return request
}, (error) => {
    console.log(error)
    return Promise.reject(error);
})

instance.interceptors.response.use((response) => {
    return response
}, (error) => {
    if (error.response && error.response.status === 401) {
        // Token 过期或无效：清除本地 Token，跳转登录页
        localStorage.removeItem('token')
        // 跳转到登录页（根据项目路由配置调整）
        window.location.href = '/login'
        ElMessage.error('登录已过期，请重新登录')
    }
    return Promise.reject(error)
})

export default instance